# -*- coding: utf-8 -*-
import random
import re
from collections import Counter

import gradio as gr
import jieba.posseg as pseg
import pymysql
from zhipuai import ZhipuAI
from datetime import datetime

# 获取当前日期
today = datetime.today()

# 格式化为 YYYY年MM月DD日
formatted_date = today.strftime("%Y年%m月%d日")

client = ZhipuAI(api_key="adc6f8692fcc4d295fddd69bc4fe6b6b.puTcpWRFYUdcNcT8")

category_list = ['熊猫', '北欧海盗', '六星', '赛霸', '肌肉博士', '马泰时刻', '元气码头', '海德力', 'on', '肌肉科技',
                 '诺特兰德', '必第能量', '康比特', '训练怪兽', '紫光优健', 'allmax', 'foyes', '科派诺', '荒野健康']
chat_history = []
prohibition_list = ['姐养', '男人', '熊猫', '北欧海盗', '六星', '赛霸', '肌肉博士', '马泰时刻', '元气码头', '海德力', 'on', '肌肉科技',
                 '诺特兰德', '必第能量', '康比特', '训练怪兽', '紫光优健', 'allmax', 'foyes', '科派诺', '荒野健康','蛋白粉','蛋白','补剂','水泥袋','老婆']


def get_negative_positive_comment(corpus, rows_comments, selected_option):
    if len(rows_comments) >= 1000:
        sample_rows = random.sample(rows_comments, 1000)
    else:
        sample_rows = rows_comments
    for row in sample_rows:
        row = row[0]
        row = row.lower()
        corpus += row + "\n"
    jieba_list = []
    for index, row in enumerate(rows_comments):
        row = row[0]
        row = row.lower()
        row = clean_text(row)
        text_list = [word for word, flag in pseg.cut(row) if flag in ['n']]
        jieba_list.extend(text_list)
    # 关键字过滤，只保留长度大于等于2的词
    jieba_list = [word for word in jieba_list if len(word) >= 2 and word not in prohibition_list]
    word_freq = Counter(jieba_list)

    # 获取词频排名前五的关键字
    top_five_keywords = word_freq.most_common(30)

    # 将前五名关键字放到一个列表里
    top_five_words = [word for word, freq in top_five_keywords]

    return corpus, jieba_list, word_freq, top_five_words


def remove_short_elements(input_list):
    filtered_list = [element for element in input_list if len(element) >= 2]
    return filtered_list


def clean_text(text):
    # 使用正则表达式匹配非中文、非阿拉伯数字、非大小写字母的字符
    cleaned_text = re.sub(r'[^\u4e00-\u9fa5a-zA-Z0-9]', '', text)
    return cleaned_text


def process_radio(selected_option, user_input, start_time='1970-1-1', end_time='2126-12-31'):
    print('评论内容...')
    print(selected_option)
    if not start_time:
        start_time = '1970-1-1'
    if not end_time:
        end_time = '2126-12-31'

    DB_CONFIG = {
        'host': 'rm-2zea30h4sh8g15zd1ho.mysql.rds.aliyuncs.com',
        'port': 3306,
        'user': "root",
        'password': 'Ds2024@()833429',
        'database': "douyinpinglun"
    }
    mydb = pymysql.connect(**DB_CONFIG)
    cursor = mydb.cursor()
    # 查看评论内容,
    query_comment_text = f"""
               SELECT DISTINCT 评论内容
               FROM 视频评论表 a join 抖音视频表 b on a.关联视频表id=b.id
               WHERE (评论内容 LIKE '%{selected_option}%')
               AND (b.视频发布时间_2 >= '{start_time}')
               AND (b.视频发布时间_2 <= '{end_time}')
           """
    print(query_comment_text)
    cursor.execute(query_comment_text)
    comment_text = cursor.fetchall()
    # 查看评论数量
    query_comment_all_number = f"""
                SELECT count(a.评论内容) FROM 视频评论表 a join 抖音视频表 b on a.关联视频表id=b.id
               WHERE (评论内容 LIKE '%{selected_option}%')
               AND (b.视频发布时间_2 >= '{start_time}')
               AND (b.视频发布时间_2 <= '{end_time}')
                """
    cursor.execute(query_comment_all_number)
    comment_all_number = cursor.fetchone()[0]
    # 正面评论数量
    query_comment_positive_number = f"""
                    SELECT count(评论内容) FROM 视频评论表 a join 抖音视频表 b on a.关联视频表id=b.id where (评论内容 LIKE '%{selected_option}%')
               AND a.情感分类='正面' AND (b.视频发布时间_2 >= '{start_time}')
               AND (b.视频发布时间_2 <= '{end_time}')
                    """
    cursor.execute(query_comment_positive_number)

    positive_comments_num = int(cursor.fetchall()[0][0])

    # 负面评论数量
    query_comment_negative_number = f"""
                    SELECT count(评论内容) FROM 视频评论表 a join 抖音视频表 b on a.关联视频表id=b.id where (评论内容 LIKE '%{selected_option}%')
               AND a.情感分类='负面' AND (b.视频发布时间_2 >= '{start_time}')
               AND (b.视频发布时间_2 <= '{end_time}')
                    """
    cursor.execute(query_comment_negative_number)
    negative_comments_num = int(cursor.fetchall()[0][0])
    query_comment_positive = f""" SELECT DISTINCT  评论内容
FROM 视频评论表 a join 抖音视频表 b on a.关联视频表id=b.id
WHERE (评论内容 LIKE '%{selected_option}%')
               AND a.情感分类='正面' AND (b.视频发布时间_2 >= '{start_time}')
               AND (b.视频发布时间_2 <= '{end_time}')"""
    print(query_comment_positive)
    cursor.execute(query_comment_positive)
    positive_rows_comments = cursor.fetchall()
    print(positive_rows_comments,
          '-----------------------------------------------------------------------------------------------')

    query_comment_negative = f"""  SELECT DISTINCT  评论内容
FROM 视频评论表 a join 抖音视频表 b on a.关联视频表id=b.id
WHERE (评论内容 LIKE '%{selected_option}%')
               AND a.情感分类='负面' AND (b.视频发布时间_2 >= '{start_time}')
               AND (b.视频发布时间_2 <= '{end_time}')  """
    cursor.execute(query_comment_negative)
    negative_rows_comments = cursor.fetchall()
    # 归纳大模型的语料corpus
    corpus = f'接下来的内容是{selected_option}这个品牌的用户评论和评论中出现次数最多的关键词,请仔细阅读语料:\n'
    # 确保 rows 列表有足够的记录
    corpus = corpus + '正面评论: '
    corpus, jieba_list_positive, word_freq, positive_top_five_words = get_negative_positive_comment(corpus,
                                                                                                    positive_rows_comments,
                                                                                                    selected_option)
    corpus = corpus + '负面评论: '
    corpus, jieba_list_negative, word_freq, negative_top_five_words = get_negative_positive_comment(corpus,
                                                                                                    negative_rows_comments,
                                                                                                    selected_option)
    corpus_basic_positive_keywords = "  ".join(positive_top_five_words)
    corpus_basic_negative_keywords = "  ".join(negative_top_five_words)
    corpus = corpus + "该品牌的正向评论的关键字:  " + corpus_basic_positive_keywords + '\n'
    corpus = corpus + "该品牌的负向评论的关键字:  " + corpus_basic_negative_keywords + '\n'
    if not user_input:
        user_input = '根据并输出几条代表性的评论,谈一下产品的优缺点,并针对产品的未来发展给出发展建议'
    # 生成文本输出
    corpus = corpus + f"\n\n请用中文回答下面这个问题问题: {user_input}"
    # corpus += f"\n用户的输入: {user_input}\n"
    print(corpus)
    yield 'AI正在思考..........', ''  # 返回词云图和初始文本
    response = client.chat.completions.create(
        model="GLM-4-Flash",
        messages=[
            {"role": "system",
             "content": "你是一个乐于回答各种问题的小助手，你的任务是提供专业、准确、有洞察力的建议。,如果语料内容为空,就直接回答没有详细资料即可,不知道的不用回答"},
            {"role": "user", "content": f"{corpus}"}
        ],
        stream=True,
    )
    positive_and_negative = positive_comments_num + negative_comments_num
    try:
        comment_surver = (
            f'截止到{formatted_date},关于{selected_option}这个搜索关键字,\n在抖音上发布时间为{start_time}到{end_time}这段时间内的视频:",\n抖音评论数据库中共有{comment_all_number}条评论,除了中性评论以外,正向评论加上负向评论共有{positive_and_negative}条,其中:\n正向评论有{positive_comments_num}条,占比为{positive_comments_num / positive_and_negative:.2%}\n负向评论有{negative_comments_num}条,占比为{negative_comments_num / positive_and_negative:.2%}\n'
            f'\n该品牌正向评论的关键字:\n{corpus_basic_positive_keywords}\n\n该品牌负向评论的关键字:\n{corpus_basic_negative_keywords}\n')
    except Exception as e:
        print(e)
        comment_surver = ''
    result_text = ""
    for chunk in response:
        top_hundred_text = chunk.choices[0].delta
        if top_hundred_text.content:
            result_text += top_hundred_text.content
            yield comment_surver, result_text

    cursor.close()
    mydb.close()


# 使用 gr.Blocks 创建界面
with gr.Blocks() as iface:
    gr.Markdown("## 大众事业部抖音评论AI分析系统\n")

    # 单选框
    radio = gr.Radio(
        choices=category_list,
        label="请选择一个品类",
        value=category_list[12]
    )

    # 输入框
    user_input = gr.Textbox(label="可以直接按回车看分析结果,也可以询问AI问题")
    # 日期选择
    with gr.Row():
        start_time = gr.DateTime(include_time=False, type="string", label="请选择视频发布时间-开始时间,默认是1970-1-1")
        end_time = gr.DateTime(include_time=False, type="string", label="请选择视频发布时间-结束时间,默认是2126-12-31")

    with gr.Row():
        # 提交按钮
        submit_button = gr.Button("提交", size="lg")
        # 重置按钮
        reset_button = gr.Button("重置", size="lg")

    # 输出框
    with gr.Column():
        output1 = gr.Textbox(label="评论概况")
        output2 = gr.Textbox(label="AI分析结果(仅供参考)")

    # 监听提交按钮的点击事件
    submit_button.click(
        fn=process_radio,
        inputs=[radio, user_input, start_time, end_time],
        outputs=[output1, output2]
    )

    # 监听重置按钮的点击事件
    reset_button.click(
        fn=lambda: [""] + [""] + [""] + ["1970-01-01", "2126-12-31"],
        outputs=[user_input, output1, output2, start_time, end_time]
    )

    # 按回车提交输入
    user_input.submit(
        fn=process_radio,
        inputs=[radio, user_input, start_time, end_time],
        outputs=[output1, output2]
    )

iface.launch(server_name="0.0.0.0", server_port=7861)
